const useApiRes = require('../common/apiRes')
const asyncHandler = require("express-async-handler");
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');
const path = require('path');
const { UPLOAD_PATH, BASE_APP_URL } = require('../../tools/helper');
const dayjs = require('dayjs');
const { fetchOne,insert} = require('../../tools/db/query')
// 获取打印任务
exports.getHtmlById = asyncHandler(async (req, res, next) => {
    const { id } = req.query;
    if (!id) {
        return useApiRes.fail(res, 'id不能为空');
    }
    const result = await fetchOne('SELECT * FROM print_logs WHERE id = ?', [id]);
    return useApiRes.success(res, result);
})




// 打印HTML
exports.printHtml = asyncHandler(async (req, res, next) => {
    const params = req.body;
    const { printerName, html, width, height, templateName } = params;
    if(!printerName || !html || !width || !height || !templateName){
        return useApiRes.fail(res, '打印机名称，模板名称，HTML，宽度，高度不能为空');
    }

    // 打印参数
    if(params.printOptions && typeof params.printOptions === 'string'){
        params.printOptions = JSON.parse(params.printOptions); // 将字符串转换为对象
        if(typeof params.printOptions !== 'object'){
            return useApiRes.fail(res, '[printOptions]-打印参数格式错误');
        }
    } else {
        params.printOptions = {};
    }
    // 生成唯一ID用于标识此次打印任务
    const uuid = uuidv4();
    // 检查打印窗口是否存在且未被销毁
    if (!global.PRINT_WINDOW || global.PRINT_WINDOW.isDestroyed()) {
        return useApiRes.fail(res, '打印窗口不可用，请重启应用');
    }

    const printOptions = Object.assign({
        uuid: uuid,
    }, params, params.printOptions)
    
    delete printOptions.html
    delete printOptions.printOptions
    try {
        const result = await insert('INSERT INTO print_logs (uuid,printerName,status,html,width,height,templateName,createTime,printOptions) VALUES (?,?,?,?,?,?,?,?,?)', [
           uuid,
           printerName,
           'waiting',
           html,
           width,
           height,
           templateName,
           dayjs().format('YYYY-MM-DD HH:mm:ss'),
           JSON.stringify(printOptions)
        ])
        console.log("printHtml.result", result?.id);
        if(!result?.id){
            return useApiRes.fail(res, '打印任务创建失败');
        }
        return useApiRes.success(res, {
            message: '打印任务创建成功',
            uuid: uuid,
            id: result.id // 返回自增ID
        });
    } catch (error) {
        console.error('打印处理出错:', error);
        return useApiRes.fail(res, '打印处理失败: ' + error.message, error);
    }
})


// 打印模板
exports.printByTemplate = asyncHandler(async (req, res, next) => {
    const { templateId, data, id, printToPDF } = req.body;
    console.log("printToPDF", printToPDF);
    // 检查打印窗口是否存在且未被销毁
    if (!global.PRINT_WINDOW || global.PRINT_WINDOW.isDestroyed()) {
        return useApiRes.fail(res, '打印窗口不可用，请重启应用');
    }
    try {
        // 如果提供了HTML文本，可以直接加载
        printerWindow.window.loadURL(BASE_APP_URL + `/html-print.html?id=${id}`);
        // 等待页面加载完成
        await new Promise((resolve) => {
            printerWindow.window.webContents.once("did-finish-load", resolve);
        });
        console.log("页面加载完成");
        // 给页面一点时间来渲染内容
        await new Promise(resolve => setTimeout(resolve, 300));
        // 生成PDF
        const pdfData = await printerWindow.window.webContents.printToPDF({
            printBackground: true,
            landscape: false,
            pageSize: {
                width: 40,  // 微米单位 (40mm = 40000微米)
                height: 30  // 微米单位 (30mm = 30000微米)
            },
            marginsType: 1, // 0 = default, 1 = none, 2 = minimum
            scaleFactor: 100, // 缩放比例 100%
            preferCSSPageSize: true, // 优先使用CSS中定义的页面尺寸
        });
        // 保存PDF文件以供检查 Y-M-D
        const outputDir = path.join(UPLOAD_PATH, dayjs().format('YYYY-MM-DD'));
        // 确保目录存在
        if (!fs.existsSync(outputDir)) {
            fs.mkdirSync(outputDir, { recursive: true });
        }
        const filePath = path.join(outputDir, `print-${id}.pdf`);
        fs.writeFileSync(filePath, pdfData);
        console.log('PDF文件保存成功:', filePath);
        return useApiRes.success(res, {
            message: '打印处理成功',
            pdfPath: filePath,
            id: id
        });
    } catch (error) {
        console.error('打印处理出错:', error);
        return useApiRes.fail(res, '打印处理失败: ' + error.message, error);
    }





});




